package org.example.ruoxing_admin_springboot3.service.user;

import jakarta.annotation.Resource;
import org.example.ruoxing_admin_springboot3.dao.UserInfoDao;
import org.example.ruoxing_admin_springboot3.dao.VerificationCodeDao;
import org.example.ruoxing_admin_springboot3.exceptionHandleUtils.ExceptionHandleUtils;
import org.example.ruoxing_admin_springboot3.httpResponseResult.ResponseResult;
import org.example.ruoxing_admin_springboot3.mapper.UserInfoMapper;
import org.example.ruoxing_admin_springboot3.mapper.VerificationCodeMapper;
import org.example.ruoxing_admin_springboot3.utils.JWTUtils;
import org.example.ruoxing_admin_springboot3.utils.StringValidatorUtils;
import org.example.ruoxing_admin_springboot3.dto.UserInfoDto;
import org.springframework.stereotype.Service;

import java.util.List;
/**
 * @description 用户登陆相关的服务类
 * @author 莫若省
 * @createTime 2024/5/6
*/
@Service
public class UserLoginService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private VerificationCodeMapper verificationCodeMapper;
    /**
     * @description 用户登陆的方法
     * @author 莫若省
     * @createTime 2024/5/6
    */
   public ResponseResult<Object> userLogin(UserInfoDto userLoginInfo) {
       try{
           //用户密码校验
           String userPassword = userLoginInfo.getUserPassword();
           if (StringValidatorUtils.isEmpty(userPassword)) {
               return ResponseResult.WARN("用户密码参数不能为空!");
           }
           //查询验证码是否存在
           VerificationCodeDao verificationCodeDao = verificationCodeMapper.selectVerificationCodeById(userLoginInfo.getVerificationCodeId());
           if (verificationCodeDao == null) {
               return ResponseResult.WARN("验证码失效,请重新获取!");
           }
           //根据用户账号查询用户信息
           List<UserInfoDao> userInfoDao = userInfoMapper.getCurrentUserInfoList(userLoginInfo);
           if (userInfoDao.isEmpty()) {
               return ResponseResult.WARN("用户账号不存在!");
           }
           //判断密码是否正确
           UserInfoDao user = userInfoDao.getFirst();
           if (!user.getUserPassword().equals(userPassword)) {
               return ResponseResult.WARN("用户密码错误!");
           }
           //生成token
           JWTUtils.Token tokenMap = JWTUtils.createTokenMap(user);
           user.setUserCurrentToken(tokenMap.getToken());
           //更新用户token
           userInfoMapper.updateUserTokenByUserId(user);
           return  ResponseResult.SUCCESS(tokenMap);
       }catch (Exception e){
           ExceptionHandleUtils.reportException(e, "用户登陆异常!");
           return ResponseResult.ERROR();
       }
   }
}
